package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author 沐辰
 * @version v1.0
 * @description:
 * @project _2306_two_Oject
 * @Date 2023/9/18 15:05
 * @company qf
 */
public class BaseController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通过用户的访问路径：获取需要访问的方法名称
        String methodName = request.getParameter("method");
        try {
            //反射获取类对象
            Class clazz = this.getClass();
            //通过反射获取方法对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //反射获取这个对象的返回值，也就是请求转发或重定向跳转页面的路径
            //"forward""redirect"
            String jumpUrl = (String) method.invoke(this, request, response);
            if (jumpUrl != null && !"".equals(jumpUrl)) {
                String[] split = jumpUrl.split(":");
                if ("forward".equals(split[0])) {
                    request.getRequestDispatcher(split[1]).forward(request,response);
                } else if ("redirect".equals(split[0])){
                    response.sendRedirect(split[1]);
                } else {
                    request.getRequestDispatcher(jumpUrl).forward(request,response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
